<script lang="tsx" setup>
/**
 *  采购订单制单
 */
import {nextTick, reactive, ref} from "vue"
import {definePageModel, PageModel} from "@/frame/view/layout/page-model/constructor.ts"
import {defineDialogForm, DialogForm} from "@/frame/components/base/dialog-form/constructor.ts"
import {defineSheetForm, SheetForm} from "@/frame/components/base/sheet-form/constructor.ts"
import PageAsideTable from "@/frame/view/layout/page-aside-table/index.vue"
import {getCode} from "@/utils/get-code"
import {CodeRuleTypeEnum} from "@/utils/enum"
import {processRequest} from "@/frame/apis/request"

/**
 * 定义emit
 */
const emit = defineEmits<{
  (e: "confirm"): void
}>()

/**
 * 下拉列表
 */
const reflections = reactive<{
  goodsList: any[];
  supplierList: any[];
}>({
  goodsList: [],
  supplierList: []
})

/**
 * 获取物料列表
 */
const getGoodsList = async () => {
  const result: any = await processRequest.get("/api/Goods", {
    IsEnable: true,
    currentPage: 1,
    pageSize: 9999
  })
  reflections.goodsList = result.dataList
}

/**
 * 获取供应商列表
 */
const getSupplierList = async () => {
  const result: any = await processRequest.get("/api/Supplier", {
    currentPage: 1,
    pageSize: 9999
  })
  reflections.supplierList = result.dataList
}

getGoodsList()
getSupplierList()

/**
 * 弹窗实例
 */
const dialogFormRef = ref()
const dialogFormConfig = defineDialogForm({
  width: "1200px",
  title: "采购订单制单"
})

/**
 * 表单实例
 */
const sheetFormModelRef = ref()
const form = defineSheetForm<any>({
  async bindData(data: any) {
    if (!data.id) {
      data.code = await getCode(CodeRuleTypeEnum.采购订单)
    }
    return data
  },
  labelWidth: "90px",
  els: [
    {
      label: "单据编码",
      eType: "el-input",
      prop: "code",
      renderFn(data) {
        return <span>{data.code} </span>
      }
    },
    {
      label: "流转卡号",
      eType: "el-input",
      prop: "cardNo",
      props: {
        placeholder: "请输入流转卡号",
        clearable: true
      }
    },
    {
      label: "供应商",
      eType: "el-select",
      prop: "supplierId",
      props: {
        placeholder: "请选择供应商",
        clearable: true
      },
      optionsData: {
        reflect: "supplierList",
        label: "name",
        value: "id"
      }
    },
    {
      label: "备注",
      eType: "el-input",
      prop: "remark",
      props: {
        placeholder: "备注",
        clearable: true
      }
    },
    {
      label: "附件",
      eType: "el-upload",
      prop: "file",
      props: {
        action: "/development/anqin/api/Upload",
        limit: 1
      }
    }
  ]
})

/**
 * 页面实例
 */
const pageModelRef = ref()
const config = definePageModel<any>({
  url: "",
  getImmediate: false,
  programForm: {
    els: [
      {
        label: "新增数据",
        eType: "el-button",
        props: {
          type: "primary"
        },
        event: "add"
      }
    ]
  },
  table: {
    page: {
      enable: true,
      pageSize: 20
    },
    props: {
      stripe: false,
      border: false
    },
    operation: {
      width: 80,
      props: {
        fixed: "right"
      },
      els: [
        {
          eType: "el-button",
          label: "删除",
          event: "delete",
          props: {
            type: "primary",
            link: true
          },
          hide: false
        }
      ]
    },
    els: [
      {
        label: "物料",
        prop: "goodsId",
        minWidth: 120,
        renderFn(data) {
          /**
           * 监听修改
           */
          const handleInput = (value: any) => {
            data.goodsId = value
          }

          return <el-select modelValue={data.goodsId} onUpdate:modelValue={handleInput}>
            {
              reflections.goodsList.map((item: any) => {
                return <el-option label={item.name} value={item.id}/>
              })
            }
          </el-select>
        }
      },
      {
        label: "采购数量",
        prop: "number_Purchase",
        minWidth: 120,
        renderFn(data) {
          /**
           * 监听修改
           */
          const handleInput = (value: any) => {
            data.number_Purchase = value
          }

          return <el-input modelValue={data.number_Purchase} onUpdate:modelValue={handleInput}/>
        }
      },
      {
        label: "备注",
        prop: "remark",
        minWidth: 120,
        renderFn(data) {
          /**
           * 监听修改
           */
          const handleInput = (value: any) => {
            data.remark = value
          }

          return <el-input modelValue={data.remark} onUpdate:modelValue={handleInput}/>
        }
      }
    ]
  }
})

/**
 * 显示
 */
const show = () => {
  nextTick(() => {
    dialogFormRef.value.show()
    nextTick(() => {
      sheetFormModelRef.value.initFormData()
      pageModelRef.value.setTableData([{
        rowKey: 1
      }])
    })
  })
}

/**
 * 新增
 */
const handleAdd = async () => {
  const tableData = await pageModelRef.value.getTableData()
  if (tableData.length > 0){
    tableData.push({
      rowKey: tableData[tableData.length - 1].rowKey + 1
    })
  } else {
    tableData.push({
      rowKey: 1
    })
  }
  pageModelRef.value.setTableData(tableData)
}

/**
 * 删除
 */
const handleDelete = async (row: any) => {
  let tableData = await pageModelRef.value.getTableData()
  tableData = tableData.filter((item: any) => item.rowKey !== row.rowKey)
  pageModelRef.value.setTableData(tableData)
}

/**
 * 提交
 */
const handleClick = async () => {
  const formData = await sheetFormModelRef.value.getFormData()
  const tableData = await pageModelRef.value.getTableData()
  await processRequest.post("/api/PurchaseOrder",
      {
        ...formData,
        items: tableData
      }
  )
  emit('confirm')
  dialogFormRef.value.close()
}

/**
 * 暴露
 */
defineExpose({
  show
})
</script>

<template>
  <DialogForm ref="dialogFormRef" :dialogFormModel="dialogFormConfig">
    <template #default>
      <div style="height: 500px;display: flex;">
        <PageAsideTable>
          <template #aside>
            <SheetForm ref="sheetFormModelRef" :SheetFormModel="form" :reflections="reflections"/>
          </template>
          <template #table>
            <PageModel ref="pageModelRef" :PageModel="config" @add="handleAdd" @delete="handleDelete"/>
          </template>
        </PageAsideTable>
      </div>
      <div style="text-align: right;">
        <el-button type="primary" @click="handleClick">提交</el-button>
      </div>
    </template>
  </DialogForm>
</template>